import { Box, Text, useColorModeValue, Input, Icon, Button, Column, Row, Radio, useToast } from "native-base"
import { useEffect, useState, useContext } from "react"
import Ionicons from 'react-native-vector-icons/Ionicons'
import appColor from "../../utils/appColor"
import Request from '../../utils/Request'
import { TokenContext } from '../Context'



// nastool配置页面
const NtConfig = ({ navigation }) => {
  const { updateToken } = useContext(TokenContext)
  const toast = useToast()

  const [formData, setFormData] = useState({ server: '', account: '', password: '' })
  const onChangeVal = (prop, val) => {
    setFormData((v) => {
      const newFormData = { ...v }
      newFormData[prop] = val
      return newFormData
    })
  }
  const [sslType, setSSLType] = useState('http://')

  // 保存nt配置
  const saveNtConfig = () => {
    let server = formData.server
    let baseUrl = ''
    if (server.endsWith('/')) {
      server = server.slice(0, -1)
    }
    if (server.includes('http')) { } else {
      server = sslType + server
    }
    baseUrl = server + '/api/v1'
    Request.post('/config/nt', { baseUrl, account: formData.account, password: formData.password }).then((res) => {
      toast.show({
        title: "保存成功",
        placement: "top"
      })
      setSyncCookieBtnVisible(formData.account ? true : false);

    }).catch(e => {
      if (e.toString().includes('401')) {
        updateToken('')
      }
    })
  }

  const [syncCookieBtnVisible, setSyncCookieBtnVisible] = useState(false)
  const asyncCookie = () => {
    Request.post('/config/nt/asyncCookie').then((res) => {
      toast.show({
        title: res.message,
        placement: "top"
      })
    }).catch(e => {

    })
  }

  const fetchNtConfig = () => {
    Request.get('/config/nt').then((res) => {
      let regRes = res.data.baseUrl.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/)
      let formd = {
        server: regRes && regRes[2] || '',
        account: res.data.account,
        password: res.data.password
      }
      if (res.data.account) setSyncCookieBtnVisible(true);

      setFormData(formd)
      if (res.data.baseUrl.includes('https')) {
        setSSLType('https://')
      } else {
        setSSLType('http://')
      }
    }).catch(e => {
      if (e.toString().includes('401')) {
        updateToken('')
      }
    })
  }

  useEffect(() => {
    fetchNtConfig()
  }, [])

  const pageBg = useColorModeValue(appColor.lightbg, appColor.darkbg)

  return (
    <Box w={'100%'} h={'100%'} bgColor={pageBg}>
      <Column space={5} w={{ base: "75%" }} mx={'auto'} mt={10}>
        <Input
          InputLeftElement={
            <Icon as={<Ionicons name="server-outline" />} size={5} ml="2" color="muted.400" />
          }
          type='text'
          returnKeyType={'next'}
          value={formData.server}
          onChangeText={(v) => onChangeVal('server', v)}
          placeholder="nastool服务器域名或ip" />
        <Input
          InputLeftElement={
            <Icon as={<Ionicons name="person-outline" />} size={5} ml="2" color="muted.400" />
          }
          type='text'
          returnKeyType={'next'}
          value={formData.account}
          onChangeText={(v) => onChangeVal('account', v)}
          placeholder="nastool账号,需要有下载/订阅权限" />
        <Input
          type="text"
          InputLeftElement={
            <Icon as={<Ionicons name='key-outline' />} size={5} ml="2" color="muted.400" />
          }
          returnKeyType={'done'}
          value={formData.password}
          onChangeText={(v) => onChangeVal('password', v)}
          placeholder="密码" />

        <Row>
          <Text mr={4}>类型</Text>
          <Radio.Group
            name="httpType"
            accessibilityLabel="http type"
            colorScheme="yellow"
            value={sslType}
            style={{ display: 'flex', flexDirection: 'row' }}
            onChange={nextValue => {
              setSSLType(nextValue);
            }}>
            <Radio shadow={2} size={'sm'} value="http://">http</Radio>
            <Box w={10}></Box>
            <Radio shadow={2} size={'sm'} value="https://">https</Radio>
          </Radio.Group>
        </Row>
        <Box mt={10}>
          {syncCookieBtnVisible ? <Button mb={5} onPress={asyncCookie}>从NasTool同步Cookie</Button> : null}
          <Button onPress={saveNtConfig}>保 存</Button>
        </Box>

      </Column>
    </Box>
  )
}


export default NtConfig